package org.example.test7;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet("/doLoginServlet")
public class DoLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 读取用户数据（从user.properties文件）
        Properties prop = new Properties();
        InputStream is = getServletContext().getResourceAsStream("/user.properties");
        if (is != null) {
            prop.load(is);
        }

        // 验证登录
        if (prop.containsKey(username) && prop.getProperty(username).equals(password)) {
            // 登录成功，跳回首页并提示
            response.getWriter().write("<script>alert('登录成功！'); window.location.href='index.jsp';</script>");
        } else {
            // 登录失败，返回登录页
            response.getWriter().write("<script>alert('用户名或密码错误！'); window.location.href='login.jsp';</script>");
        }
    }
}